package com.hemj.upload;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;

@RestController
@RequestMapping("/upload")
public class FileUploadController {

    private static final String UPLOAD_DIR = "uploads/"; // 上传文件保存的目录
    private static final String BASE_URL = "http://localhost:8080/uploads/"; // 文件URL前缀

    /**
     * 处理文件分片上传
     * 
     * @param file - 上传的文件分片
     * @param chunkIndex - 当前分片的索引（第几块）
     * @param totalChunks - 总分片数
     * @param fileName - 文件名
     * @return 上传结果或文件的URL地址
     */
    @PostMapping("/chunk")
    public ResponseEntity<String> uploadChunk(
            @RequestParam("file") MultipartFile file,
            @RequestParam("chunkIndex") int chunkIndex, 
            @RequestParam("totalChunks") int totalChunks, 
            @RequestParam("fileName") String fileName) {
        
        try {
            // 创建保存分片的文件目录
            File uploadDir = new File(UPLOAD_DIR);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            // 构建当前分片的文件路径
            String chunkFileName = fileName + ".part" + chunkIndex;
            File chunkFile = new File(UPLOAD_DIR + chunkFileName);
            file.transferTo(chunkFile); // 保存分片

            // 如果是最后一个分片，合并所有分片，并返回文件的URL
            if (chunkIndex == totalChunks - 1) {
                mergeChunks(fileName, totalChunks);
                String fileUrl = BASE_URL + fileName;
                return ResponseEntity.ok(fileUrl); // 返回文件的URL
            }

            return ResponseEntity.ok("分片上传成功: " + chunkIndex);

        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("上传失败");
        }
    }

    /**
     * 合并所有分片文件为完整文件
     * 
     * @param fileName - 合并后文件名
     * @param totalChunks - 总分片数
     */
    private void mergeChunks(String fileName, int totalChunks) {
        try {
            File mergedFile = new File(UPLOAD_DIR + fileName);
            try (FileOutputStream fos = new FileOutputStream(mergedFile, true)) {
                for (int i = 0; i < totalChunks; i++) {
                    File chunkFile = new File(UPLOAD_DIR + fileName + ".part" + i);
                    Files.copy(chunkFile.toPath(), fos); // 合并分片到最终文件
                    chunkFile.delete(); // 合并后删除分片文件
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
